import { defineStore } from 'pinia';
import { ref, computed,watch } from 'vue';
import { User } from '../types';
import { API_CONFIG } from '../config/apiConfig';
import router from '../router';

// 创建统一的会话过期处理方法
function handleSessionExpired() {
  // 清理用户数据
  localStorage.removeItem('userInfo');
  document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  
  // 使用 replace 而不是 push 来防止用户通过浏览器后退返回
  router.replace('/');
}

export const useUserStore = defineStore('user', () => {
  
  const users = ref<User[]>([]); // 清空伪数据
  const currentPage = ref(1); // 当前页码
  const pageSize = ref(10); // 每页数量
  const total = ref(0); // 总记录数

  const searchQuery = ref('');

  // 异步获取用户列表
 const fetchUsers = async () => {
    try {
      const url = new URL(`${API_CONFIG.BASE_URL}/user/page`);
      url.searchParams.append('pageNo', `${currentPage.value}`); // 使用模板字符串转为 string
      url.searchParams.append('pageSize', `${pageSize.value}`); 
      const response = await fetch(url, {
        method: 'GET',
        credentials: 'include'
      });
      const result = await response.json();
      if (result.code === "0") {
        users.value = result.data.dataList.map((user: User) => ({
          id: user.id,
          nickname: user.nickname,
          username: user.username,
          roleId: user.roleId,
          roleName: user.roleName,
          researchGroupId: user.researchGroupId,
          researchGroupName: user.researchGroupName // 正确映射API返回的账号字段
        }));
        total.value = parseInt(result.data.total);
      }else if(result.code === '0001') {
        handleSessionExpired();
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
    }
  };

  // 过滤用户数据
  const filteredUsers = computed(() => {
    if (!searchQuery.value) return users.value;
    const query = searchQuery.value;
    return users.value.filter(user => 
      user.id.includes(query) ||
      user.nickname.includes(query) ||
      user.username.includes(query)
    );
  });
  
  // 监听搜索查询变化，重置页码
  watch(searchQuery, () => {
    currentPage.value = 1;
  });

  // 计算过滤后的总数量
  const filteredTotal = computed(() => {
    return searchQuery.value ? filteredUsers.value.length : total.value;
  });

  return {
    users,
    searchQuery,
    currentPage,
    pageSize,
    total,
    fetchUsers,
    filteredUsers,
    filteredTotal
  };
});